package com.leadingsoft.pwxk.sync;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.leadingsoft.pwxk.dto.FileInfoDto;
import com.leadingsoft.pwxk.model.BaseInfo;
import com.leadingsoft.pwxk.model.FileDetail;
import com.leadingsoft.pwxk.model.ProcessChart;
import com.leadingsoft.pwxk.repository.BaseInfoRepository;
import com.leadingsoft.pwxk.repository.FileDetailRepository;
import com.leadingsoft.pwxk.repository.ProcessChartRepository;
import com.leadingsoft.pwxk.utils.ConnectUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author ysh
 * @desc 附件补偿机制
 */
@Component
@Slf4j
public class DealFileErrorTask {

	private static String sourceUrl = "http://10.102.33.36:8080";

	private static String agentUrl = "http://10.37.18.9:8080/data";

	@Autowired
	FileDetailRepository fileDetailRepository;

	@Autowired
	ProcessChartRepository processChartRepository;

	@Autowired
	BaseInfoRepository baseInfoRepository;

	/*@Scheduled(cron = "#{syncProperties['fileCron']}")*/
	public void dealFileError() {
		log.info("进入处理附件异常任务");
		List<ProcessChart> ps = processChartRepository.findByPathIsNull();
		log.debug("" + ps.size());
		ps.forEach(t -> {
			String fileurl = t.getFileurl().replace(sourceUrl, agentUrl);
			FileInfoDto dto = ConnectUtil.sendRequest(fileurl);
			if (null != dto) {
				t.setPath(dto.getPath());
				t.setNewfilename(dto.getFilename());
				t.setDealresult(true);
			} else {
				t.setDealresult(false);
			}
			Integer num = t.getDealnum() == null ? 0 : t.getDealnum();
			t.setDealnum(++num);
			t.setIsdeal(true);
			processChartRepository.save(t);
		});
		List<FileDetail> fs = fileDetailRepository.findByPathIsNull();
		log.debug("" + fs.size());
		fs.forEach(t -> {
			String fileurl = t.getFileUrl().replace(sourceUrl, agentUrl);
			FileInfoDto dto = ConnectUtil.sendRequest(fileurl);
			if (null != dto) {
				t.setPath(dto.getPath());
				t.setNewfilename(dto.getFilename());
				t.setDealresult(true);
			} else {
				t.setDealresult(false);
			}
			Integer num = t.getDealnum() == null ? 0 : t.getDealnum();
			t.setDealnum(++num);
			t.setIsdeal(true);
			fileDetailRepository.save(t);
		});
		List<BaseInfo> bs = baseInfoRepository.findByPathIsNull();
		log.debug("" + bs.size());
		bs.forEach(t -> {
			String fileurl = t.getFileurl().replace(sourceUrl, agentUrl);
			FileInfoDto dto = ConnectUtil.sendRequest(fileurl);
			if (null != dto) {
				t.setPath(dto.getPath());
				t.setNewfilename(dto.getFilename());
				t.setDealresult(true);
			} else {
				t.setDealresult(false);
			}
			Integer num = t.getDealnum() == null ? 0 : t.getDealnum();
			t.setDealnum(++num);
			t.setIsdeal(true);
			baseInfoRepository.save(t);
		});
		log.info("结束处理附件异常任务");
	}
}
